<template>
  <div class="page-container">
    <!-- 联系手机号 -->
    <!-- <Number /> -->
    <!-- 手机验证码 -->
    <!-- <NumberConfirm /> -->
    <!-- 查询预约订单 -->
    <div v-if="isShow" class="button-wrapper">
      <Number v-model="phone_number" />
      <!-- 手机验证码 -->
      <NumberConfirm v-model="code" />
    </div>

    <div class="button-wrapper">
      <up-button
        text="查询预约订单"
        class="button primary-button"
        type="primary"
        size="large"
        @click="Search"
      >
        <span class="button-text">查询预约订单</span>
      </up-button>
    </div>
    <!-- 乘车预约订单 -->
    <div class="header-section illustrate">
      <div class="illustrate-left"></div>
      <div class="illustrate-body">
        <span class="header-title">乘车预约订单</span>
      </div>
      <div class="illustrate-right"></div>
    </div>
    <p class="reservation-note">
      预约说明：如需修改预约信息，需在预约日期当天0点前
    </p>

    <!-- 预约订单列表 -->
    <div
      v-for="(item, index) in filteredInformation"
      :key="item.id"
      class="order-item"
    >
      <p class="reservation-type large-text centered-text extra-large">
        {{
          item.reservation_type === 0
            ? "去程日期"
            : item.reservation_type === 1
            ? "返程日期"
            : "往返日期"
        }}
      </p>
      <div class="button-group">
        <up-button
          class="cancel button danger-button"
          text="取消预约"
          size="large"
          @click="Cancel(item, index)"
        >
          <span class="button-text">取消预约</span>
        </up-button>
        <template v-if="item.reservation_type == 0">
          <p class="godate large-text centered-text extra-large">
            {{ formatDate(item.fromDate) }} {{ dayOfWeek(item.fromDate) }}
            <span v-if="showPeople">{{ item.passenger_count }}人</span>
          </p>
        </template>
        <template v-else-if="item.reservation_type == 1">
          <p class="godate large-text centered-text extra-large">
            {{ formatDate(item.returnDate) }}
            {{ dayOfWeek(item.returnDate) }}
            <span v-if="showPeople">{{ item.passenger_count }}人</span>
          </p>
        </template>
        <template v-else-if="item.reservation_type == 10">
          <p class="godate large-text centered-text extra-large">
            {{ formatDate(item.fromDate) }}
            {{ dayOfWeek(item.fromDate) }}->
            {{ formatDate(item.returnDate) }}
            {{ dayOfWeek(item.returnDate) }}
            <span v-if="showPeople">{{ item.passenger_count }}人</span>
          </p>
        </template>
        <up-button
          class="change button warning-button"
          text="修改预约"
          type="warning"
          size="large"
          @click="Confirm(item)"
        >
          <span class="button-text">修改预约</span>
        </up-button>
      </div>
      <div class="separator"></div>
    </div>

    <div class="button-wrapper">
      <up-button
        text="去预约"
        class="button primary-button"
        type="primary"
        size="large"
        @click="Confirm"
      >
        <span class="button-text">去预约</span>
      </up-button>
    </div>
    <div class="header-section illustrate">
      <div class="illustrate-left"></div>
      <div class="illustrate-body">
        <span class="header-title">历史订单</span>
      </div>
      <div class="illustrate-right"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import Number from "./travel/Number.vue";
import NumberConfirm from "./travel/NumberConfirm.vue";

let showPeople = ref(true);
let information = reactive([]);
let isShow = ref(false);
const code = ref("");
const phone_number = ref("");
const authToken = ref("");

function getToken() {
  let token = uni.getStorageSync("token");
  authToken.value = token;
  return token;
}
onLoad(async (e) => {
  let token = getToken();
  if (!token) {
    isShow.value = true;
  } else {
    await Search();
  }
});

const dayOfWeek = computed(() => {
  const days = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  return (dateStr) => {
    const d = new Date(dateStr);
    return days[d.getDay()];
  };
});

const formatDate = computed(() => {
  return (dateStr) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString();
  };
});

const filteredInformation = computed(() => {
  return information.filter(
    (item) =>
      item.reservation_type === 0 ||
      item.reservation_type === 1 ||
      item.reservation_type === 10
  );
});

async function Search() {
  if (!authToken.value) {
    let c_code = await confirm();
    if (c_code == -1) {
      return;
    }
    // return;
  }
  uni.request({
    url: "/api/order/list",
    method: "get",
    header: {
      Authorization: `Bearer ${authToken.value}`,
    },
    success: (res) => {
      if (res.data.code === 200) {
        information.splice(0, information.length);
        res.data.data.forEach((item) => {
          information.push({
            id: parseInt(item.id),
            returnDate: item.return_date,
            fromDate: item.go_date,
            passenger_count: item.passenger_count,
            reservation_type: parseInt(item.reservation_type) || 0,
            passenger_name: item.passenger_name,
            pickup_location_id: item.pickup_location_id,
          });
        });
        showPeople.value = true;
        nextTick(() => {
          console.log("DOM updated");
        });
      } else {
        alert("查询失败");
        console.error("API Error:", res.data.message || res.data.error);
      }
    },
    fail: (err) => {
      alert("查询失败");
      console.error("Request Error:", err);
    },
  });
}

const confirm = async () => {
  let token = uni.getStorageSync("token");
  if (!token) {
    // 验证验证码
    const smsResponse = await uni.request({
      url: "/api/user/sms/login",
      method: "POST",
      data: {
        phone_number: phone_number.value,
        code: code.value,
      },
    });

    if (!smsResponse || !smsResponse.data || smsResponse.data.code !== 200) {
      alert(smsResponse.data.message);
      return -1;
    }
    token = smsResponse.data.data.access_token;
    uni.setStorageSync("token", token);
    authToken.value = token;
    return 0;
  }
};

function Cancel(order, index) {
  const token = getToken();
  const requestData = {
    id: order.id,
  };

  uni.request({
    url: "/api/order/delete?id=" + order.id,
    method: "post",
    header: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    data: {},
    success: (res) => {
      if (res.data.code === 200) {
        alert("取消成功");
        information.splice(index, 1);
      } else {
        alert("取消失败");
        console.error("取消失败:", res.data.message || res.data.error);
      }
    },
    fail: (err) => {
      alert("请求失败");
      console.error(err);
    },
  });
}

function Confirm(order) {
  uni.setStorageSync("order_info", JSON.stringify(order));
  uni.redirectTo({ url: "/" });
}
</script>

<style scoped>
.page-container {
  font-family: Arial, sans-serif;
  padding: 20px;
  text-align: center;
}

.button-wrapper {
  margin-bottom: 20px;
}

.button {
  border-radius: 8px;
  padding: 12px 24px;
  cursor: pointer;
  border: none;
  transition: background-color 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
}

.primary-button {
  background-color: #007bff;
  color: white;
}

.primary-button:hover {
  background-color: #0056b3;
}

.warning-button {
  background-color: #ffc107;
  color: black;
}

.warning-button:hover {
  background-color: #d39e00;
}

.danger-button {
  background-color: #dc3545;
  color: white;
}

.danger-button:hover {
  background-color: #c82333;
}

.illustrate {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px 0;
}

.illustrate-left,
.illustrate-right {
  flex: 1;
  height: 3px;
  background-color: #ccc;
}

.illustrate-body {
  padding: 0 20px;
  font-weight: bold;
  font-size: 22px;
}

.header-title {
  position: relative;
  display: inline-block;
}

.reservation-note {
  color: #666;
  font-size: 16px;
  margin-bottom: 20px;
}

.reservation-type {
  font-weight: bold;
  margin-bottom: 15px;
  font-size: 24px;
}

.godate {
  margin-bottom: 10px;
  line-height: 1.5;
  font-size: 22px;
}

.large-text {
  font-size: 20px;
}

.centered-text {
  text-align: center;
}

.extra-large {
  font-size: 26px;
}

.separator {
  height: 2px;
  background-color: #ccc;
  margin: 20px 0;
}

.order-item {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 15px;
}

.button-text {
  padding: 0 10px;
}
</style>
